// pages/login-phone/login-phone.js
const request = require('../../utils/request.js')
const api = require('../../config/api.js');
const { shareOptions } = require('../../utils/access.js');
import { getStorage, jump, setStorage, goBack } from "../../utils/utils"

let timer = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: '',
    showRight: false,
    showVcode: true,
    disabled: false,
    time: 60
  },
  /**
   * 获取验证码
   */
  async getSmsCode() {
    const that = this;
    const { mobile } = this.data;
    const res = await request.post(`${api.smsSend}`, {
      appId: 'bc-recyling',
      phone: mobile,
      requestId: 123454667
    })
    this.setData({
      showVcode: false
    })
    let interval = setInterval(() => {
      that.setData({
        time: that.data.time - 1
      })
      if ((that.data.time) <= 0) {
        that.setData({
          time: 60,
          showVcode: true
        })
        clearInterval(interval)
      }
    }, 1000)
  },
  /**
   * 获取验证码
   */
  sendCode() {
    const { mobile, showRight } = this.data;
    if (!(/^1[3456789]\d{9}$/.test(mobile))) {
      wx.showToast({
        title: '手机号输入有误，请重新输入',
        icon: 'none',
        duration: 2000,
      });
      return
    }
    if (!showRight) {
      return
    }
    this.getSmsCode();

  },
  /**
   * 点击登录
   */
  async startLogin(form) {
    const that = this;
    const { disabled, mobile, code } = this.data;
    if (!disabled) return
    const swapData = getStorage('swapData');
    const userInfo = getStorage('userInfo');
    let params = {
      phone: mobile,
      captcha: code,
      encryptedData: swapData?.encryptedData,
      ivStr: swapData?.iv,
      icon: userInfo?.avatarUrl,
      gender: userInfo?.gender,
      nickName: userInfo?.nickName,
      sessionKey: swapData?.sessionKey
    };

    const res = await request.post(api.authBind, params)
    const { data, httpStatus } = res || {}
    if (httpStatus !== 200) {
      wx.showToast({
        title: '登录失败',
        icon: 'none',
        duration: 2000,
      });
    } else {
      setStorage('token', data?.token);
      setStorage('phone', data?.phone);
      jump('index')
    }
  },
  /**
   * 获取输入的验证码
   */
  bindCodeInput(e) {
    const { showRight } = this.data;
    const { value } = e.detail;
    this.setData({
      code: e.detail.value.trim(),
      disabled: showRight && value.length
    })
  },
  /**
   * 获取输入的手机号
   */
  bindMobileInput(e) {
    const { showRight, code } = this.data;
    const { value } = e.detail;
    this.setData({
      mobile: e.detail.value.trim(),
      showRight: value && (value.length === 11),
      disabled: showRight && code.length
    })
  },
  /**
   * 清空手机号
   */
  handleClear() {
    this.setData({
      value: '',
      disabled: false
    })
  },
  // 返回
	handleBack(){
		goBack()
    timer && clearTimeout(timer);
  },
  onUnload: function () {},
  // 用户点击右上角分享
	onShareAppMessage(e) {
		return shareOptions('default', e)
	},
})